//
//  GYXBaseViewController.swift
//  GYXWeibo
//
//  Created by Twisal on 2016/11/8.
//  Copyright © 2016年 Twisal. All rights reserved.
//

import UIKit

class GYXBaseViewController: UIViewController {
    var tableView: UITableView?
    var refreshControl: GYXRefreshControl?
    var isPullup: Bool = false
//    var userLogon = true
    var visitorDict : [String : String]?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        GYXNetworkManager.shared.userLogon ? loadData() : ()
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
    }
   
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    /// 重写title的didSet方法
    override var title: String? {
        didSet {
            naviItem.title = title
        }
    }
    
    lazy var naviBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    lazy var naviItem = UINavigationItem()
    
    
    /// 加载数据
    func loadData() {
        refreshControl?.endRefreshing()
    }
}


// MARK: - 监听事件
extension GYXBaseViewController {
    
    @objc fileprivate func login() {
        print("用户登录")
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    @objc fileprivate func register() {
        print("用户注册")
    }
    
    @objc fileprivate func loginSuccess(note: Notification) {
        naviItem.leftBarButtonItem = nil
        naviItem.rightBarButtonItem = nil
        // view设为nil, 会重新调用loadView, viewDidLoad登方法
        view = nil
        // viewDidLoad重新调用, 需要移除通知
        NotificationCenter.default.removeObserver(self)
    }
    
}

// MARK: - 页面布局
extension GYXBaseViewController {
    
    /// 初始化UI
    fileprivate func setupUI() {
        view.backgroundColor = UIColor.cz_random()
        // 关闭自动缩进的20个点
        automaticallyAdjustsScrollViewInsets = false
        setupNavigationBar()
        // 判断是否登录
        GYXNetworkManager.shared.userLogon ? setupTableView():setupVistorView()
        
    }
    
    
    /// 初始化导航条
    private func setupNavigationBar() {
        view.addSubview(naviBar)
        naviBar.items = [naviItem]
        // 1>, 设置整个背景的渲染颜色
        naviBar.barTintColor = UIColor.cz_color(withHex: 0xf6f6f6)
        // 2>, 设置标题的颜色
        naviBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.darkGray]
        // 3>, 设置左右两边按钮的颜色
        naviBar.tintColor = UIColor.orange
    }
    
    /// 设置未登录时的访客视图
    private func setupVistorView() {
        let vistorView = GYXVistorView(frame: view.bounds)
        view.insertSubview(vistorView, belowSubview: naviBar)
        vistorView.visitorInfo = visitorDict
        vistorView.loginBtn.addTarget(self, action: #selector(login), for: .touchUpInside)
        vistorView.registerBtn.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        naviItem.leftBarButtonItem = UIBarButtonItem(title: "注册", target: self, action: #selector(register))
        naviItem.rightBarButtonItem = UIBarButtonItem(title: "登录", target: self, action: #selector(login))
    }
    
    
    /// 设置登录后的页面
    func setupTableView() {
        
        tableView = UITableView(frame: view.bounds, style:.plain)
        view.insertSubview(tableView!, belowSubview: naviBar)
        // 设置数据源和代理
        tableView?.dataSource = self
        tableView?.delegate = self
        
        // 设置tableView的内容缩进
        tableView?.contentInset = UIEdgeInsets(top: naviBar.bounds.height, left: 0, bottom:tabBarController?.tabBar.bounds.height ?? 49 , right: 0)
        tableView?.scrollIndicatorInsets = (tableView?.contentInset)!
        
        // 添加刷新控件
        refreshControl = GYXRefreshControl()
        tableView?.addSubview(refreshControl!)
        refreshControl?.addTarget(self, action:#selector(loadData), for: .valueChanged)
        
        
    }
}


// MARK: - UITableViewDataSource, UITableViewDelegate
extension GYXBaseViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // 1,获取当前的行
        let row = indexPath.row
        // 2,获取当前的组
        let section = indexPath.section;
        
        if row < 0 || section < 0 {
            return
        }
        // 3,获取最后的一组
        let lastSection = tableView.numberOfSections - 1
        // 4,获取最后一组的最后一行
        let lastRow = tableView.numberOfRows(inSection: lastSection) - 1
        
        if section == lastSection && row == lastRow && !isPullup {
            print("上拉刷新")
            isPullup = true
            loadData()
        }
        
//        print("section --\(section)")
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 10
    }
}
